#!/bin/bash

# 组要安装xvfb x11vnc使用东软代理即可
# sudo apt install xvfb x11vnc
# 手动安装
# 包地址：ftp：/sdk_docker/xvfb_1.20.13-1ubuntu1~20.04.8_amd64.deb
# 安装命令
# sudo dpkg -i xvfb_1.20.13-1ubuntu1~20.04.8_amd64.deb
# 错误信息：Error response from daemon: invalid pool request: Pool overlaps with other one on this address space
# 解决方法：docker network prune

#ftp info
WORK_PATH=$(readlink -f ${0} | xargs dirname)
script_name=$(basename $0)
FTP_IP="10.1.19.164"
FTP_PORT="21"
FTP_ARENE_NAME="tagldev"
FTP_NAME="dten_repo"
FTP_PASS="arene_IVI-=00"
FTP_ARENE_URL="ftp://${FTP_ARENE_NAME}:arene%5FIVI-%3D00@${FTP_IP}:${FTP_PORT}/sdk_docker"
FTP_BEV_URL="ftp://${FTP_NAME}:arene%5FIVI-%3D00@${FTP_IP}:${FTP_PORT}"
FTP_BEV_RELEASE_URL="${FTP_BEV_URL}/Release"
FTP_IC_IMAGES_URL="${FTP_BEV_URL}/gitlab_bev_ci/images"
FTP_IC_SDK_URL="${FTP_BEV_URL}/gitlab_bev_ci/sdk"
IC_SDK_CORE="dn-package-sysroots-core2-64.tar.gz"
IC_SDK_X86="dn-package-sysroots-x86_64.tar.gz"
IMAGE_TARGET_CONF="image.conf"

#variable for sdk
ENV_PATH="${WORK_PATH}/env"
SDK_TARGET_PATH="${WORK_PATH}/env/sdk"
BEV_DOCKER_BACKUP_PATH="${ENV_PATH}/bev_docker_backup"
SDK_TARGET_CONF="sdk.conf"
SDK_VERSION_FILE="${SDK_TARGET_PATH}/version-core2-64-arene-linux"
DEFAULT_POKY_CONTAINER="arene/poky-container:ubuntu-20.04"
DOCKER_CONFIGS_URL="http://10.169.5.10/bevs3cdc/dn-bevs3-cdc/dn-cdc-lvgvm-misc-simulator.git"
DOCKER_CONFIGS_PATH="${ENV_PATH}/dn-cdc-lvgvm-misc-simulator"
DOCKER_CONFIGS_FILE="${DOCKER_CONFIGS_PATH}/config/docker.env"
DOCKER_SCRIPT="${DOCKER_CONFIGS_PATH}/dn-sim.sh"
BEV_DEBUG_RUNTIME_DOCKER="arene-image-cockpit-cdc-genericx86-64-debug.tar.bz2"
BEV_RELEASE_RUNTIME_DOCKER="arene-image-cockpit-cdc-genericx86-64.tar.bz2"
BEV_DEBUG_RUNTIME_IMAGE="dn-bevs3cdc-runtime-dbg"
BEV_RELEASE_RUNTIME_IMAGE="dn-bevs3cdc-runtime-rel"

DATE=$(date +%Y%m%d)
YOCTO_BUILD_DATE="yocto-build-${DATE}"
PASSWORD_FLAG=0
USER_PASSWORD='wang'
USER_PASSWORD=$(echo ${USER_PASSWORD} | sed 's/\$/\\$/g') 
########################################################################################################################

function log()
{
    echo "----------------------------------------------------------------------------------------------------------------"
    echo ${1}
    echo ""
}

function install_sdk() 
{
    if [ -e ${ENV_PATH} ]; then
        log "[NORMAL] ----[${ENV_PATH}] existed !!!----"
    else
        mkdir ${ENV_PATH}
        log "[NORMAL] --create ${ENV_PATH} OK!"
    fi

    log "[NORMAL ] wget --spider --no-host-directories --no-parent --cut-dirs=2 --no-remove-listing --recursive --level=2 -P ${ENV_PATH} ${FTP_BEV_RELEASE_URL}"
    wget --spider --no-host-directories --no-parent --cut-dirs=2 --no-remove-listing --recursive --level=2 -P ${ENV_PATH} ${FTP_BEV_RELEASE_URL} >&/dev/null
    if [[ $? -ne 0 ]]; then 
      log "[ERROR] Failed to get file .listing !!!"
      exit 1
    fi
    if [[ -e ${ENV_PATH}/.listing ]]; then
        local docker_ver_list=$(grep -E "^d" ${ENV_PATH}/.listing | awk '{print $9}' | uniq | sort -V -r | sed 's/\r/ /g')
        if [[ ${docker_ver_list} ]]; then
            echo "Which sdk version do you want to update?"
            PS3="Please enter your choice:"
            select docker_ver in ${docker_ver_list[@]} ; do
                break;
            done
            if [[ ${docker_ver} ]]; then
                cd ${ENV_PATH}
                # download sdk
                rm -f arene-toolchain-cockpit-cdc-*-genericx86-64.sh
                log "[NORMAL ] wget ${FTP_BEV_RELEASE_URL}/${docker_ver}/sdk/x86-ubuntu/arene-toolchain-cockpit-cdc-*-genericx86-64.sh"
                wget -S -N ${FTP_BEV_RELEASE_URL}/${docker_ver}/sdk/x86-ubuntu/arene-toolchain-cockpit-cdc-*-genericx86-64.sh
                if [[ $?  -ne 0 ]]; then
                    log "[ERROR ] wget SDK File ERROR !!!."
                    return 1
                fi
                chmod +x arene-toolchain-cockpit-cdc-*-genericx86-64.sh
                SDK_NAME=$(ls arene-toolchain-cockpit-cdc-*-genericx86-64.sh)
                log "[NORMAL ] SDK file = [${SDK_NAME}]."
                # remove old sdk
                log "[NORMAL ] rm -f ${SDK_TARGET_PATH} ."
                rm -rf ${SDK_TARGET_PATH}

                cd ${WORK_PATH}
                echo "Please select the installation method:"
                echo "0 : Install using docker [${DEFAULT_POKY_CONTAINER}]"
                echo "1 : Installing on Ubuntu"
                read -p "Please enter your options:" installopt
                if [[ ${installopt} == 0 ]]; then
                    log "[NORMAL ] Install SDK using ${DEFAULT_POKY_CONTAINER}."
                    if [[ $(docker images -q ${DEFAULT_POKY_CONTAINER}) ]]; then
                        #install sdk
                        log "[NORMAL ] ------ install sdk start ------."
                        docker run --rm -v ~:/home/hosthome:ro -v $(pwd):/workdir \
                            --name poky-$(id -un) \
                            --workdir=/workdir \
                            ${DEFAULT_POKY_CONTAINER} ./env/${SDK_NAME} -y -d ./env/sdk
                    else
                        log "[ERR ] Please install [${DEFAULT_POKY_CONTAINER}] images first !!!."
                        exit 1
                    fi
                elif [[ ${installopt} == 1 ]]; then
                    local system_ver=$(cat /etc/issue | cut -d " " -f2)
                    if [[ ${system_ver} < "22.04.9" ]] || [[ ${system_ver} > "20.04.0" ]];then
                        ./env/${SDK_NAME} -y -d ./env/sdk
                    else
                        log "[ERR ] The system version is [${system_ver}] (22.04 > ver > 20.04)!!!."
                        exit 1
                    fi
                else
                    log "[ERROR ] your options=[${installopt}] ERROR !!!."
                    exit 1
                fi
                grep -rni "version" ${SDK_VERSION_FILE}
            else
                log "[ERROR ] check sdk version=[${docker_ver}] ERROR !!!."
                exit 1
            fi
        else
            log "[ERROR ] There is no sdk version to upgrade !!!."
            exit 1
        fi
    else
        log "[ERROR ] ${ENV_PATH}/.listing file does not exist ERROR !!!."
        exit 1
    fi
}

function install_ic_sdk() 
{
    if [ -e ${ENV_PATH}/sdk ]; then
        log "[NORMAL] ----[${ENV_PATH}/sdk] existed ----"
    else
        log "[ERR] --[${ENV_PATH}/sdk] Non-existence !!!"
        return 1
    fi

    cd ${ENV_PATH}
    log "[NORMAL ] rm -f ${SDK_TARGET_CONF} ."
    rm -f ${SDK_TARGET_CONF}

    log "[NORMAL ] wget -O ${SDK_TARGET_CONF} ${FTP_IC_SDK_URL}/${SDK_TARGET_CONF} ."
    wget -O ${SDK_TARGET_CONF} ${FTP_IC_SDK_URL}/${SDK_TARGET_CONF}
    if [[ $?  -ne 0 ]]; then
        log "[ERROR ] wget -O ${SDK_TARGET_CONF} ${FTP_IC_SDK_URL}/${SDK_TARGET_CONF} ERROR !!!."
        return 1
    fi
    SDK_VERSION=$(grep SDK_VERSION ${SDK_TARGET_CONF} | cut -d = -f 2)
    if [[ ${SDK_VERSION} ]];then
        log "[NORMAL ] wget -O ${IC_SDK_CORE} ${FTP_IC_SDK_URL}/${SDK_VERSION}/${IC_SDK_CORE} ."
        wget -O ${IC_SDK_CORE} ${FTP_IC_SDK_URL}/${SDK_VERSION}/${IC_SDK_CORE}
        if [[ $?  -ne 0 ]]; then
            log "[ERROR ] wget -O ${IC_SDK_CORE} ${FTP_IC_SDK_URL}/${SDK_VERSION}/${IC_SDK_CORE}  ERROR !!!."
            return 1
        else
            log "[NORMAL ] tar -zxf ${IC_SDK_CORE} -C ./sdk/sysroots/core2-64-arene-linux ."
            tar -zxf ${IC_SDK_CORE} -C ./sdk/sysroots/core2-64-arene-linux
        fi

        log "[NORMAL ] wget -O ${IC_SDK_X86} ${FTP_IC_SDK_URL}/${SDK_VERSION}/${IC_SDK_X86} ."
        wget -O ${IC_SDK_X86} ${FTP_IC_SDK_URL}/${SDK_VERSION}/${IC_SDK_X86}
        if [[ $?  -ne 0 ]]; then
            log "[ERROR ] wget -O ${IC_SDK_X86} ${FTP_IC_SDK_URL}/${SDK_VERSION}/${IC_SDK_X86} !!!."
            return 1
        else
            log "[NORMAL ] tar -zxf ${IC_SDK_X86} -C ./sdk/sysroots/x86_64-arenesdk-linux ."
            tar -zxf ${IC_SDK_X86} -C ./sdk/sysroots/x86_64-arenesdk-linux
        fi
    else
        log "[ERROR ] CHECK SDK_VERSION=[${SDK_VERSION}] ERROR !!!."
        return 1
    fi
}

function git_clone_config_repo() 
{
    log "[NORMAL ] git clone ${DOCKER_CONFIGS_URL} ${DOCKER_CONFIGS_PATH}."
    git clone ${DOCKER_CONFIGS_URL} ${DOCKER_CONFIGS_PATH}
    if [[ $? -ne 0 ]]; then
      log "[ERROR] git clone ${DOCKER_CONFIGS_URL} ${DOCKER_CONFIGS_PATH} !!!"
      exit 1
    fi
    git -C ${DOCKER_CONFIGS_PATH} pull
    if [[ $? -ne 0 ]]; then
      log "[ERROR] git -C ${DOCKER_CONFIGS_PATH} pull !!!"
      exit 1
    fi
    git -C ${DOCKER_CONFIGS_PATH} checkout master
    if [[ $? -ne 0 ]]; then
      log "[ERROR] git -C ${DOCKER_CONFIGS_PATH} checkout master !!!"
      exit 1
    fi

    sed -i "s@sudo -v@echo '${USER_PASSWORD}' | sudo -S -v@" ${DOCKER_CONFIGS_PATH}/setup.sh
    echo ${USER_PASSWORD} | sudo -S apt -v >/dev/null 2>&1
    ${DOCKER_CONFIGS_PATH}/setup.sh

    sed -ri "s@WORK_DIR=~/hmifw_share@WORK_DIR=${WORK_PATH}@g" ${DOCKER_CONFIGS_FILE}
    sed -i 's|DOCKER_IMAGE_RUNTIME_NAME=.*|DOCKER_IMAGE_RUNTIME_NAME=dn-bevs3cdc-runtime-dbg|g' ${DOCKER_CONFIGS_FILE}

    sed -i '/^function start_container() {$/a\    # set virtual display \
    Xvfb_info=$(ps -ef | grep Xvfb) \
    if [[ ${Xvfb_info} =~ "Xvfb :2 -screen 0 1280x720x24" ]]; then \
        echo "[info] Xvfb is exist info = [${Xvfb_info}]" \
    else \
        echo "[info] sh = [Xvfb :2 -screen 0 1280x720x24 &]" \
        Xvfb :2 -screen 0 1280x720x24 & \
        sleep 30 \
    fi \
    export DISPLAY=:2.0 \
    sleep 5' ${DOCKER_SCRIPT}
    sed -i '/launch_weston \${WESTON_INI}/a\    logger "INFO" "Check the Weston startup status, please wait for about 3 minutes." \
    local retry_num=0 \
    while ! pgrep weston >/dev/null; do \
        logger "INFO" "Check weston startup status [${retry_num}] times." \
        sleep 10 \
        if [[ ${retry_num} == 20 ]]; then \
            logger "ERROR" "weston startup ERROR !!!" \
            exit 1 \
        fi \
        retry_num=$((retry_num + 1)) \
    done \
    logger "INFO" "Weston startup Succeeded."' ${DOCKER_SCRIPT}
    sed -i 's|docker stop ${CONTAINER_NAME} > /dev/null|docker stop ${CONTAINER_NAME} > /dev/null 2>\&1|g' ${DOCKER_SCRIPT}
    sed -i '/logger "ERROR" "Failed to stop container."/a\        if pgrep weston >/dev/null; then \
            kill -9 $(pgrep weston) \
        fi' ${DOCKER_SCRIPT}
    sed -i '/logger "ERROR" "Failed to kill weston."/a\        if pgrep weston >/dev/null; then \
            kill -9 $(pgrep weston) \
        fi' ${DOCKER_SCRIPT}
    sed -i '/Delete temporary files no longer needed/a\    logger "INFO" "Check the Weston stop status, please wait for about 1 minutes." \
    local retry_num=0 \
    while pgrep weston >/dev/null; do \
        logger "INFO" "Check weston stop status [${retry_num}] times." \
        sleep 10 \
        if [[ ${retry_num} == 10 ]]; then \
            logger "ERROR" "weston stop ERROR !!!" \
            exit 1 \
        fi \
        retry_num=$((retry_num + 1)) \
    done \
    logger "INFO" "Weston stop Succeeded."' ${DOCKER_SCRIPT}

    # set sudo password
    sed -i "/^function start_container() {$/a\    echo '${USER_PASSWORD}' | sudo -S -v" ${DOCKER_SCRIPT}
    sed -i "/^function stop_container() {$/a\    echo '${USER_PASSWORD}' | sudo -S -v" ${DOCKER_SCRIPT}
    sed -i "/^function kill_container() {$/a\    echo '${USER_PASSWORD}' | sudo -S -v" ${DOCKER_SCRIPT}
    local delete_line_no=$(grep -n 'device /dev/dri:/dev/dri' ${DOCKER_SCRIPT} | head -1 | cut -d ":" -f1)
    sed -i "${delete_line_no}d" ${DOCKER_SCRIPT}
    # sed -ri 's@^\s+--device /dev/dri:/dev/dri @1111111@g' dn-sim.sh
    # sed -ri '/1111111/d' dn-sim.sh
    local system_ver=$(cat /etc/issue | cut -d " " -f2)
    if [[ ${system_ver} =~ "22.04" ]]; then
        sed -i 's/--cgroup-parent/--cgroupns/g' ${DOCKER_SCRIPT}
    fi
}

function Execute_install_script() 
{
    local Xvfb_info=$(ps -ef | grep [X]vfb)
    if [[ ${Xvfb_info} =~ "Xvfb :2 -screen 0 1280x720x24" ]]; then
        log "[info] Xvfb is exist info = [${Xvfb_info}]"
    else
        local xvfb_path=$(which Xvfb)
        if [[ -z ${xvfb_path} ]]; then
            sudo apt update
            sudo apt install xvfb x11vnc
        else
            log "[info] sh = [Xvfb :2 -screen 0 1280x720x24 &]"
            Xvfb :2 -screen 0 1280x720x24 &
            sleep 30
        fi
    fi
    if [[ ${1} ]]; then
        source ${DOCKER_CONFIGS_FILE}
        log "[NORMAL ] docker rmi images=${DOCKER_REGISTRY}/${DOCKER_IMAGE_RUNTIME_NAME}:${DOCKER_IMAGE_RUNTIME_TAG}."
        docker rmi ${DOCKER_REGISTRY}/${DOCKER_IMAGE_RUNTIME_NAME}:${DOCKER_IMAGE_RUNTIME_TAG}
        log "[info] sh = [${DOCKER_SCRIPT} load ${1}]"
        (${DOCKER_SCRIPT} load ${1})
        if [[ $?  -ne 0 ]]; then
            echo "[info] sh = [${DOCKER_SCRIPT} load ${1}] ERROR !!!"
            exit 1
        fi
    fi
    log "[info] sh = [${DOCKER_SCRIPT} start]"
    (${DOCKER_SCRIPT} start 2>&1)
    if [[ $?  -ne 0 ]]; then
        echo "[info] sh = [${DOCKER_SCRIPT} start] ERROR !!!"
        exit 1
    fi
}

function install_check() 
{
    if [ -e ${ENV_PATH} ]; then
        log "[NORMAL] ----[${ENV_PATH}] existed !!!----"
    else
        mkdir ${ENV_PATH}
        log "[NORMAL] --create ${ENV_PATH} OK!"
    fi

    local dn_docker_status=$(docker ps | grep dn-sim)
    if [[ -n ${dn_docker_status} ]]; then
        (${DOCKER_SCRIPT} stop 2>&1)
        if [[ $?  -ne 0 ]]; then
            log "[info] sh = [${DOCKER_SCRIPT} stop] ERROR !!!"
            exit 1
        fi
    fi
    
    local container_id=$(docker ps -a -q --filter name="dn-sim")
    if [[ -n ${container_id} ]]; then
        docker rm -f ${container_id}
    fi

    # stop host weston
    local weston_status=$(ps -ef |grep [w]eston)
    if [[ -n ${weston_status} ]]; then
        start-stop-daemon -K -p /tmp/weston.pid && {
            log "[INFO] Succeeded to stop weston."
        } || {
            log "[ERROR] Failed to stop weston."
            if pgrep weston >/dev/null; then
                kill -9 $(pgrep weston)
            fi
        }
    fi
    local retry_num=0
    while pgrep weston >/dev/null; do
        sleep 10
        if [[ ${retry_num} == 10 ]]; then
            log "[ERROR] weston stop check ERROR !!!"
            # exit 1
        fi
        retry_num=$((retry_num + 1))
    done

    log "[NORMAL] find ${BEV_DOCKER_BACKUP_PATH} -type d,f -mtime +30 -exec rm -rf {} \;-"
    find ${BEV_DOCKER_BACKUP_PATH} -type d,f -mtime +30 -exec rm -rf {} \;
}

function install_docker_env() 
{
    local REAL_BEV_DOCKER_BACKUP_PATH=""
    local REAL_FTP_BEV_RELEASE_URL=""
    local runtime_docker_name=${BEV_DEBUG_RUNTIME_DOCKER}
    local runtime_image_name=${BEV_DEBUG_RUNTIME_IMAGE}

    install_check

    if [ -e ${DOCKER_CONFIGS_PATH} ]; then
        source ${DOCKER_CONFIGS_FILE}
        # remove old docker images.
        log "[NORMAL ] docker rmi images=${DOCKER_REGISTRY}/${DOCKER_IMAGE_RUNTIME_NAME}:*."
        docker rmi $(docker images -q ${DOCKER_REGISTRY}/${DOCKER_IMAGE_RUNTIME_NAME}:*)
    fi
    
    log "[NORMAL ] wget --spider --no-host-directories --no-parent --cut-dirs=2 --no-remove-listing --recursive --level=2 -P ${ENV_PATH} ${FTP_BEV_RELEASE_URL}"
    wget --spider --no-host-directories --no-parent --cut-dirs=2 --no-remove-listing --recursive --level=2 -P ${ENV_PATH} ${FTP_BEV_RELEASE_URL} >&/dev/null
    if [[ $? -ne 0 ]]; then 
      log "[ERROR] Failed to get file .listing !!!"
      exit 1
    fi
    if [[ -e ${ENV_PATH}/.listing ]]; then
        local docker_ver_list=$(grep -E "^d" ${ENV_PATH}/.listing | awk '{print $9}' | uniq | sort -V -r | sed 's/\r/ /g')
        if [[ ${docker_ver_list} ]]; then
            echo "Which docker version do you want to update?"
            PS3="Please enter your choice:"
            select docker_ver in ${docker_ver_list[@]} ; do
                break;
            done
            if [[ ${docker_ver} ]];then
                log "[INFO ] version is [${docker_ver}] !!!."
                if [[ ${1} == 0 ]]; then
                    runtime_docker_name=${BEV_RELEASE_RUNTIME_DOCKER}
                    runtime_image_name=${BEV_RELEASE_RUNTIME_IMAGE}
                fi
                REAL_FTP_BEV_RELEASE_URL="${FTP_BEV_RELEASE_URL}/${docker_ver}/image/x86-ubuntu"
                REAL_BEV_DOCKER_BACKUP_PATH="${BEV_DOCKER_BACKUP_PATH}/${docker_ver}"
                if [ -e ${REAL_BEV_DOCKER_BACKUP_PATH} ]; then
                    log "[NORMAL] ----[${REAL_BEV_DOCKER_BACKUP_PATH}] existed !!!----"
                else
                    mkdir -p ${REAL_BEV_DOCKER_BACKUP_PATH}
                    log "[NORMAL] --create ${REAL_BEV_DOCKER_BACKUP_PATH} OK!"
                fi
                if [[ -e ${REAL_BEV_DOCKER_BACKUP_PATH}/${runtime_docker_name} ]]; then
                    echo "The current version of the docker file already exists. Do I need to download it again?"
                    echo "0 : No need to re-download"
                    echo "1 : Need to re-download"
                    read -p "Please enter your options:" opt
                else
                    opt="1"
                fi
                if [[ ${opt} == 1 ]]; then
                    if [ -e ${DOCKER_CONFIGS_PATH} ]; then
                        log "[NORMAL] ----[${DOCKER_CONFIGS_PATH}] existed !!!----"
                        log "[NORMAL ] rm -rf ${DOCKER_CONFIGS_PATH}."
                        rm -rf ${DOCKER_CONFIGS_PATH}
                    fi
                    
                    git_clone_config_repo
                    sed -ri "s|DOCKER_IMAGE_RUNTIME_TAG=.*|DOCKER_IMAGE_RUNTIME_TAG=${docker_ver}|g" ${DOCKER_CONFIGS_FILE}
                    sed -i "s|DOCKER_IMAGE_RUNTIME_NAME=.*|DOCKER_IMAGE_RUNTIME_NAME=${runtime_image_name}|g" ${DOCKER_CONFIGS_FILE}
                    # download docker
                    cd ${DOCKER_CONFIGS_PATH}
                    log "[NORMAL ] wget ${REAL_FTP_BEV_RELEASE_URL}/${runtime_docker_name}."
                    wget -S -N ${REAL_FTP_BEV_RELEASE_URL}/${runtime_docker_name}
                    if [[ $?  -ne 0 ]]; then
                        echo "[ERROR ] wget ${REAL_FTP_BEV_RELEASE_URL}/${runtime_docker_name} ERROR !!!."
                        exit 1
                    fi
                    cp ${runtime_docker_name} ${REAL_BEV_DOCKER_BACKUP_PATH}
                else
                    source ${DOCKER_CONFIGS_FILE}
                    local runtime_image_id=$(docker images -q ${DOCKER_REGISTRY}/${DOCKER_IMAGE_RUNTIME_NAME}:${DOCKER_IMAGE_RUNTIME_TAG})
                    if [[ ! ${runtime_image_id} ]] && [[ ! -e ${DOCKER_CONFIGS_PATH}/${runtime_docker_name} ]]; then
                        cp ${REAL_BEV_DOCKER_BACKUP_PATH}/${runtime_docker_name} ${DOCKER_CONFIGS_PATH}
                    fi
                fi
            else
                log "[ERROR ] check docker version =[${docker_ver}] ERROR !!!."
                exit 1
            fi
        else
            log "[ERROR ] There is no docker version to upgrade !!!."
            exit 1
        fi
    else
        log "[ERROR ] ${ENV_PATH}/.listing file does not exist ERROR !!!."
        exit 1
    fi

    Execute_install_script ${DOCKER_CONFIGS_PATH}/${runtime_docker_name}
}

function install_ic_docker() 
{
    install_check

    if [ -e ${DOCKER_CONFIGS_PATH} ]; then
        log "[NORMAL] ----[${ENV_PATH}/arene-ivi-misc-configs] existed !!!----"
    else
        git_clone_config_repo
    fi
    
    sed -i 's|DOCKER_IMAGE_RUNTIME_TAG=.*|DOCKER_IMAGE_RUNTIME_TAG=bev_ci|g' ${DOCKER_CONFIGS_FILE}

    log "[NORMAL ] wget -O ${DOCKER_CONFIGS_PATH}/${IMAGE_TARGET_CONF} ${FTP_IC_IMAGES_URL}/${IMAGE_TARGET_CONF} ."
    wget -O ${DOCKER_CONFIGS_PATH}/${IMAGE_TARGET_CONF} ${FTP_IC_IMAGES_URL}/${IMAGE_TARGET_CONF}
    if [[ $?  -ne 0 ]]; then
        log "[ERROR ] wget -O ${DOCKER_CONFIGS_PATH}/${IMAGE_TARGET_CONF} ${FTP_IC_IMAGES_URL}/${IMAGE_TARGET_CONF} ERROR !!!."
        exit 1
    fi
    IMAGE_VERSION_PATH=$(grep IMAGE_VERSION_PATH ${DOCKER_CONFIGS_PATH}/${IMAGE_TARGET_CONF} | cut -d = -f 2)
    if [[ ${IMAGE_VERSION_PATH} ]];then
        source ${DOCKER_CONFIGS_FILE}
        local runtime_file=${DOCKER_IMAGE_RUNTIME_NAME}_${DOCKER_IMAGE_RUNTIME_TAG}.tar.gz
        log "[NORMAL ] wget -O ${DOCKER_CONFIGS_PATH}/${runtime_file} ${FTP_IC_IMAGES_URL}/${IMAGE_VERSION_PATH}/${runtime_file} ."
        wget -O ${DOCKER_CONFIGS_PATH}/${runtime_file} ${FTP_IC_IMAGES_URL}/${IMAGE_VERSION_PATH}/${runtime_file}
        if [[ $?  -ne 0 ]]; then
            log "[ERROR ] wget -O ${DOCKER_CONFIGS_PATH}/${runtime_file} ${FTP_IC_IMAGES_URL}/${SDK_VERSION}/${runtime_file}  ERROR !!!."
            exit 1
        fi
        log "[NORMAL ] docker rmi images=${DOCKER_REGISTRY}/${DOCKER_IMAGE_RUNTIME_NAME}:${DOCKER_IMAGE_RUNTIME_TAG}."
        docker rmi ${DOCKER_REGISTRY}/${DOCKER_IMAGE_RUNTIME_NAME}:${DOCKER_IMAGE_RUNTIME_TAG}
        log "[NORMAL ] docker load < ${DOCKER_CONFIGS_PATH}/${runtime_file} "
        docker load < ${DOCKER_CONFIGS_PATH}/${runtime_file} 
    else
        log "[ERROR ] CHECK IMAGE_VERSION_PATH=[${IMAGE_VERSION_PATH}] ERROR !!!."
        exit 1
    fi

    Execute_install_script
}

function install_yocto_docker_outside() 
{
    install_check

    if [ -e ${DOCKER_CONFIGS_PATH} ]; then
        log "[NORMAL] ----[${DOCKER_CONFIGS_PATH}] existed !!!----"
    else
        log "[ERRPR] -- ${DOCKER_CONFIGS_PATH} does not exist !!!"
        exit 1
    fi

    rm -f ${DOCKER_CONFIGS_PATH}/arene-image-cockpit-cdc-genericx86-64-*.rootfs.tar.bz2
    log "[NORMAL ] wget ${FTP_BEV_URL}${1}"
    local docker_file=$(basename ${1})
    wget -O ${DOCKER_CONFIGS_PATH}/${docker_file} ${FTP_BEV_URL}${1}
    if [[ $?  -ne 0 ]]; then
        log "[ERROR ] wget ${FTP_BEV_URL}${1} ERROR !!!."
        return 1
    fi
    local docker_ver=${docker_file##*-}
    sed -ri "s|DOCKER_IMAGE_RUNTIME_TAG=.*|DOCKER_IMAGE_RUNTIME_TAG=${docker_ver%%.*}|g" ${DOCKER_CONFIGS_FILE}

    Execute_install_script ${DOCKER_CONFIGS_PATH}/${docker_file}
}

function install_sdk_docker_outside() 
{
    read -p "Please enter your docker path (eg:/SDK_BUILD/20250604_0.12.0.0-rc.1/20250604_0.12.0.0-rc.1_20250605-10/image/20250604_0.12.0.0-rc.1_20250605-10.tar.gz):" path
    install_check

    if [ -e ${DOCKER_CONFIGS_PATH} ]; then
        log "[NORMAL] ----[${DOCKER_CONFIGS_PATH}] existed !!!----"
    else
        log "[ERRPR] -- ${DOCKER_CONFIGS_PATH} does not exist !!!"
        exit 1
    fi

    pushd ${DOCKER_CONFIGS_PATH}
        rm -f *.tar.gz
        log "[NORMAL ] wget ${FTP_BEV_URL}${path}"
        wget ${FTP_BEV_URL}${path}
        if [[ $?  -ne 0 ]]; then
            log "[ERROR ] wget ${FTP_BEV_URL}${path} ERROR !!!."
            return 1
        fi
        image_file=$(basename ${path})
        docker load -i ${image_file}
    popd
    sed -ri "s|DOCKER_IMAGE_RUNTIME_TAG=.*|DOCKER_IMAGE_RUNTIME_TAG=${image_file/.tar.gz/}|g" ${DOCKER_CONFIGS_FILE}

    log "[info] sh = [${DOCKER_SCRIPT} start]"
    (${DOCKER_SCRIPT} start 2>&1)
    if [[ $?  -ne 0 ]]; then
        echo "[info] sh = [${DOCKER_SCRIPT} start] ERROR !!!"
        exit 1
    fi
}

function docker_restart
{
    echo ">>>>>>>>>>> docker_restart start >>>>>>>>>>>>"
    echo ${USER_PASSWORD} | sudo -S apt -v >/dev/null 2>&1
    (${DOCKER_SCRIPT} restart )
    if [[ $? -ne 0 ]]; then
        echo "[ERR ] Failed to restart docker container."
        exit 1
    fi
    sleep 10
    echo "<<<<<<<<<<< docker_restart end <<<<<<<<<<<<<"
    echo ""
}

########################################################
# main
########################################################
if [[ ${PASSWORD_FLAG} == 0 ]]; then
    read -p "Please enter your root password:" password
    log "your enter password is [${password}] !!!"
    if [[ ${USER_PASSWORD} != ${password} ]]; then
        sed -i "s|^USER_PASSWORD='asdf1234'$|USER_PASSWORD='${password}'|g" ${WORK_PATH}/${script_name}
        USER_PASSWORD=$(echo ${password} | sed 's/\$/\\$/g') 
        log "change USER_PASSWORD is [${USER_PASSWORD}] !!!"
    else
        log "USER_PASSWORD is also [${USER_PASSWORD}] !!!"
    fi
    sed -i "s|^PASSWORD_FLAG=0$|PASSWORD_FLAG=1|g" ${WORK_PATH}/${script_name}
fi
while :
do
    echo "######################################################################################"
    echo "#         Please select one of the options below to proceed                          #"
    echo "# Options:                                                                           #"
    echo "#         1   SDK install                                                            #"
    echo "#         2   DOCKER install (Use after 20241016_0.3.0.0-rc.3)                       #"
    echo "#         3   CI SDK install                                                         #"
    echo "#         4   CI DOCKER install (Use after 20241016_0.3.0.0-rc.3)                    #"
    echo "#         5   YOCTO DOCKER install (164 ftp)(Use after 20241016_0.3.0.0-rc.3)        #"
    echo "#         6   SDK BUILD DOCKER install (164 ftp)                                     #"
    echo "#         7   docker restart                                                         #"
    echo "#         0   exit                                                                   #"
    echo "######################################################################################"

    read -p "Please enter your options:" options
    echo ""
    
    case ${options} in
            1)
                log "[NORMAL] >>>>>>Install sdk Start !<<<<<<"
                install_sdk
                log "[NORMAL] >>>>>>Install sdk End  !<<<<<<"
                ;;
            2)
                read -p "Please enter your docker type (0:release 1:debug):" type
                log "[NORMAL] >>>>>>Install docker Start !<<<<<<"
                install_docker_env ${type}
                log "[NORMAL] >>>>>>Install docker End  !<<<<<<"
                ;;
            3)
                log "[NORMAL] >>>>>> IC SDK install  Start !<<<<<<"
                install_ic_sdk
                log "[NORMAL] >>>>>> IC SDK install End  !<<<<<<"
                ;;
            4)
                log "[NORMAL] >>>>>> IC DOCKER install Start !<<<<<<"
                install_ic_docker
                log "[NORMAL] >>>>>> IC DOCKER install End  !<<<<<<"
                ;;
            5)
                read -p "Please enter your docker path (eg:/YOCTO/SP19/0.11.0.0-rc.5-20250526060238/arene-image-cockpit-cdc-genericx86-64-20250526060238.rootfs.tar.bz2):" path
                log "[NORMAL] >>>>>> YOCTO DOCKER install (outside ftp) Start !<<<<<<"
                install_yocto_docker_outside ${path}
                log "[NORMAL] >>>>>> YOCTO DOCKER install (outside ftp) End  !<<<<<<"
                ;;
            6)
                log "[NORMAL] >>>>>> SDK BUILD DOCKER install (164 ftp) Start !<<<<<<"
                install_sdk_docker_outside
                log "[NORMAL] >>>>>> SDK BUILD DOCKER install (164 ftp) End  !<<<<<<"
                ;;
            7)
                log "[NORMAL] -- docker restart --"
                docker_restart
                ;;
            0)
                log "[NORMAL] --exit 0--"
                exit 0
                ;;
            *)
                log "[ERROR ] ------wrong option = [ ${options} ]!!!------"
                ;;
    esac
done
